 
  

 






<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do?Id=181 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:28:07 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
<head>
 <title>
  Java Practices -> Forward versus redirect
 </title>
 <link rel="stylesheet" type="text/css" href="../stylesheet8.css" media="all">
 
 <link rel="shortcut icon" href='../images/favicon.ico' type="image/vnd.microsoft.icon">
 <meta name="description" content="Concise presentations of java programming practices, tasks, and conventions, amply illustrated with syntax highlighted code examples.">
 
 <meta name='keywords' content='reload,forward,JSP,redirect,servlet,java,java programming,java practices,java idiom,java style,java design patterns,java coding conventions,'>
 
 
</head>
 
<body>


<div class='menu-bar'>
 
  <a href='../home/HomeAction.html' title='Table of Contents'>Home</a> |
  <a href='../vote/VoteSummaryAction-2.html' title='View Poll Results'>Poll</a> |
   
  <A href='../feedback/FeedbackAction451f-2.html?Operation=Show' title='Send Your Feedback'>Wiki</a> |
  <b><a href='../source/SourceAction-2.html' title='Grab Source Code'>Source Code</a></b><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |

  <a href='http://www.web4j.com/Java_Web_Application_Framework_Overview.jsp?From=1' title='Free Download - Java Web Application Framework'><b>WEB4J</b></a> |
  
  <a href='http://www.date4j.net/' title='Replacement for java.util.Date'><b>DATE4J</b></a> |

   <a href='../references/ReferencesAction-2.html' title='References'>Links</a>
   
  <form action='http://www.javapractices.com/search/SearchAction.do' method='get' class='search-form'>
   <input type='text' name='SearchTerms' value="" size=12 maxlength=50 class='search'>
   <input type='submit' value="Search">
  </form>
 
</div>

<P>



  

 






<p class="display-messages">

 

 

</p>


<div class="main-layout">
 
   

 




<div class='page-title'>Forward versus redirect</div>

<div class='main-body'>
 
<br>A <tt>Controller</tt> (in this context, an implementation of <tt>HttpServlet</tt>) may perform either a forward or a redirect
operation at the end of processing a request. It's important to understand the 
difference between these two cases, in particular with respect to browser reloads 
of web pages.

<p>Forward
<ul>
<li>a forward is performed internally by the servlet</li>

<li>
the browser is completely unaware that it has taken place, so its original
URL remains intact</li>

<li>
any browser reload of the resulting page will simple repeat the original request, with the original
URL</li>
</ul>
Redirect
<ul>
<li>
a redirect is a two step process, where the web application instructs the
browser to fetch a second URL, which differs from the original</li>

<li>
a browser reload of the second URL will not repeat the <i>original</i>
request, but will rather fetch the <i>second</i> URL</li>

<li>
redirect is marginally slower than a forward, since it requires two browser requests, not one</li>

<li>
objects placed in the <i>original</i> request scope are not available to
the second request</li>
</ul>

In general, a forward should be used if the operation can be safely repeated upon 
a browser reload of the resulting web page; otherwise, redirect must be used. 
<span class='highlight'>Typically, if the operation
performs an edit on the datastore, then a redirect, not a forward, is required.</span> 
This is simply to avoid the possibility of inadvertently duplicating an edit to the database.

<P>More explicitly (in terms of common <a href='http://en.wikipedia.org/wiki/SQL'>SQL</a> operations) :
<ul>
<li>for <tt>SELECT</tt> operations, use a forward
<li>for <tt>INSERT</tt>, <tt>UPDATE</tt>, or <tt>DELETE</tt> operations, use a redirect
</ul>

In HTML, a <tt>&lt;FORM&gt;</tt> tag can either <a href='http://www.w3.org/TR/html4/interact/forms.html#submit-format'><tt>GET</tt> or <tt>POST</tt></a> its data.
In this context, a <tt>GET</tt> corresponds to a <tt>SELECT</tt>-then-forward, and a <tt>POST</tt>
corresponds to an edit-then-redirect.

<P>It is strongly recommended that forms for the input of search criteria should use <tt>GET</tt>, 
while forms for editing database records should use <tt>POST</tt>.

<P><b>Example</b>

<P>This example is after the style of the <a href='http://www.web4j.com/'>WEB4J</a> Controller class. 
The important methods of the Servlet API are :
<ul>
<li><tt>ServletRequest.<a href='http://java.sun.com/javaee/5/docs/api/javax/servlet/ServletRequest.html#getRequestDispatcher(java.lang.String)'>getRequestDispatcher(String)</a></tt>
<li><tt>RequestDispatcher.<a href='http://java.sun.com/javaee/5/docs/api/javax/servlet/RequestDispatcher.html#forward(javax.servlet.ServletRequest,%20javax.servlet.ServletResponse)'>forward(request, response)</a></tt>
<li><tt>HttpServletResponse.<a href='http://java.sun.com/javaee/5/docs/api/javax/servlet/http/HttpServletResponse.html#sendRedirect(java.lang.String)'>sendRedirect(String)</a></tt>
</ul>
<br>
<PRE>

<span class='keyword'>import</span> java.io.IOException;
<span class='keyword'>import</span> javax.servlet.*;
<span class='keyword'>import</span> javax.servlet.http.*;
<span class='keyword'>import</span> hirondelle.web4j.action.Action;
<span class='keyword'>import</span> hirondelle.web4j.action.ResponsePage;
<span class='keyword'>import</span> hirondelle.web4j.request.RequestParser;
<span class='keyword'>import</span> hirondelle.web4j.model.BadRequestException;

<span class='keyword'>public</span> <span class='keyword'>class</span> RedirectForward <span class='keyword'>extends</span> HttpServlet {
  
  <span class='comment'>//..many items elided
</span>
  <span class='keyword'>@Override</span> <span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>void</span> doGet(
      HttpServletRequest aRequest, HttpServletResponse aResponse
   ) <span class='keyword'>throws</span> ServletException, IOException {
    processRequest(aRequest, aResponse);
  }

  <span class='keyword'>@Override</span> <span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>void</span> doPost(
      HttpServletRequest aRequest, HttpServletResponse aResponse
   ) <span class='keyword'>throws</span> ServletException, IOException {
    processRequest(aRequest, aResponse);
  }

  <span class='comment'>/**
  * Handle all HTTP &lt;tt&gt;GET&lt;/tt&gt; and &lt;tt&gt;POST&lt;/tt&gt; requests.
  */</span>
  <span class='keyword'>protected</span> <span class='keyword'>void</span> processRequest(
    HttpServletRequest aRequest, HttpServletResponse aResponse
  ) <span class='keyword'>throws</span> ServletException, IOException {
    RequestParser requestParser = RequestParser.getInstance(aRequest, aResponse);
    <span class='keyword'>try</span> {
      Action action = requestParser.getWebAction();
      ResponsePage responsePage = action.execute();
      <span class='keyword'>if</span> ( responsePage.getIsRedirect() ) {
        redirect(responsePage, aResponse);
      }
      <span class='keyword'>else</span> {
        forward(responsePage, aRequest, aResponse);
      }
    }
    <span class='keyword'>catch</span> (BadRequestException ex){
      <span class='comment'>//..elided
</span>      <span class='comment'>//use Response.sendError()
</span>    }
    <span class='keyword'>catch</span> (Throwable ex) {
      <span class='comment'>//..elided
</span>      <span class='comment'>//use Response.sendError()
</span>    }
  }
  
  <span class='comment'>// PRIVATE //
</span>  
  <span class='keyword'>private</span> <span class='keyword'>void</span> redirect(
    ResponsePage aDestinationPage, HttpServletResponse aResponse
  ) <span class='keyword'>throws</span> IOException {
    String urlWithSessionID = aResponse.encodeRedirectURL(aDestinationPage.toString());
    aResponse.sendRedirect( urlWithSessionID );
  }

  <span class='keyword'>private</span> <span class='keyword'>void</span> forward(
    ResponsePage aResponsePage, HttpServletRequest aRequest, HttpServletResponse aResponse
  ) <span class='keyword'>throws</span> ServletException, IOException {
    RequestDispatcher dispatcher = aRequest.getRequestDispatcher(aResponsePage.toString());
    dispatcher.forward(aRequest, aResponse);
  }
} 
</PRE>
<br>
<br>
<br>

</div>




<div class='topic-section'>See Also :</div>
<div class='main-body'>
 
  
  <a href='TopicActionae2d-2.html?Id=139'>Command objects</a> <br>
 
  
  <a href='TopicAction5f31-2.html?Id=188'>A Web App Framework - WEB4J</a> <br>
 
  
  <a href='TopicAction00cb-2.html?Id=219'>Consider Controllers for redirects</a> <br>
 
</div>


<div class='topic-section'>Would you use this technique?</div>
<div class='main-body'>
  
  <form action="http://www.javapractices.com/vote/AddVoteAction.do" method='post'>
    Yes<input type='radio' name='Choice' value='Y' >
    &nbsp;&nbsp;No<input type='radio' name='Choice' value='N'>
    &nbsp;&nbsp;Undecided<input type='radio' name='Choice' value="?" >
    &nbsp;&nbsp;<input type=submit value="Vote" >
    <input type='hidden' name='Operation' value='Apply'>
    <input type='hidden' name='TopicId' value='181'>
  </form>
</div>

<div style='height:10.0em;'></div>

 
 
</div>

  

 





<div align='center' class='legalese'>  
&copy; 2011 Hirondelle Systems |
<a href='../source/SourceAction-2.html'><b>Source Code</b></a><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |
<a href="mailto:webmaster@javapractices.com">Contact</a> |
<a href="http://creativecommons.org/licenses/by-nc-sa/1.0/">License</a> |
<a href='../apps/cjp.rss'>RSS</a>
<!-- ukey="2AC36CD2" -->
<!-- ckey="16DF3D87" -->
<br>

 Individual code snippets can be used under this <a href='../LICENSE.txt'>BSD license</a> - Last updated on June 6, 2010.<br>
 Over 150,000 unique IPs last month - <span title='Java Practices 2.6.5, Mon May 16 00:00:00 EDT 2011'>Built with</span> <a href='http://www.web4j.com/'>WEB4J</a>.<br>
 - In Memoriam : Bill Dirani -
</div>

<script src="../../www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-2633428-1";
urchinTracker();
</script>



</body>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do?Id=181 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:28:07 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
</html>
